// DlgAddNew.cpp : implementation file
//

#include "stdafx.h"
#include "financedef.h"
#include "CDataFile.h"
#include "finance.h"

#include "PageDateRange.h"
#include "PageLoginInfo.h"

#include "DlgAddNew.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif



extern CFinanceApp theApp;       

/////////////////////////////////////////////////////////////////////////////
// CDlgAddNew dialog


CDlgAddNew::CDlgAddNew(CWnd* pParent /*=NULL*/)
	: CDialog(CDlgAddNew::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDlgAddNew)
	m_pickdate = 0;
	m_stcTips = _T("");
	m_dateEnd = 0;
	m_stcDateBeg = _T("");
	//}}AFX_DATA_INIT

	m_bAdded = FALSE;
}


void CDlgAddNew::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDlgAddNew)
	DDX_DateTimeCtrl(pDX, IDC_DATE_ADD, m_pickdate);
	DDX_Text(pDX, IDC_TIPS, m_stcTips);
	DDX_DateTimeCtrl(pDX, IDC_DATE_END, m_dateEnd);
	DDX_Control(pDX, IDC_ED_CERIFICATE, m_edCerificate);
	DDX_Control(pDX, IDC_ED_BANKNAME, m_edBankName);
	DDX_Control(pDX, IDC_ED_BANKRATE, m_edBankRate);
	DDX_Control(pDX, ID_APPEND, m_btnOk);
	DDX_Control(pDX, ID_QUIT, m_btnQuit);
	DDX_Control(pDX, IDC_CMB_FLOW, m_cmbFlow);
	DDX_Control(pDX, IDC_CMB_PURPOSE, m_cmbPurpose);
	DDX_Control(pDX, IDC_CMB_OWNER, m_cmbOwner);
	DDX_Control(pDX, IDC_ED_COMMENT, m_edComment);
	DDX_Control(pDX, IDC_ED_MONEY, m_edAccount);
	DDX_Text(pDX, IDC_STC_BEGDATE, m_stcDateBeg);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CDlgAddNew, CDialog)
	//{{AFX_MSG_MAP(CDlgAddNew)
	ON_BN_CLICKED(ID_APPEND, OnAppend)
	ON_BN_CLICKED(ID_QUIT, OnQuit)
	ON_CBN_SELCHANGE(IDC_CMB_FLOW, OnSelchangeCmbFlow)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDlgAddNew message handlers

// 
//--------------------------------------------------------------
BOOL CDlgAddNew::OnInitDialog() 
{
	_variant_t		var;
	CString			csTmp;
	CString			csSQL;
	INT				iLeftSpan, iTopSpan;
		
	
	CDialog::OnInitDialog();
	
	// save origin	
	GetWindowRect( &m_dlgRect );
	INT	iScreenW = GetSystemMetrics( SM_CXSCREEN );
	if( iScreenW >= 1024 ) 
	{
		iLeftSpan = 227;
		iTopSpan = 100;
	}
	else
	{
		iLeftSpan = 112;
		iTopSpan = 3;
	}
	m_dlgRect.left	+= iLeftSpan;
	m_dlgRect.right	+= iLeftSpan;
	m_dlgRect.top		+= iTopSpan;
	m_dlgRect.bottom	+= iTopSpan;
	

	// <> Init UI	
	m_btnOk.SetIcon(IDI_EYEON, IDI_EYEOFF);
	m_btnQuit.SetIcon(IDI_RUN2, IDI_RUN3);
	
	// <> Open RecordSet
	m_pRecordset.CreateInstance(__uuidof(Recordset));
	m_pAccountset.CreateInstance(__uuidof(Recordset));
	m_pBankset.CreateInstance(__uuidof(Recordset));
	

	// <> Fill ComboBox flowclass
	try
	{
		m_pRecordset->Open("SELECT * FROM Flowclass",   
			theApp.m_pConnection.GetInterfacePtr(),	 // Get the Ptr of connect lib
			adOpenDynamic,
			adLockOptimistic,
			adCmdText);
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}
	
	m_cmbFlow.ResetContent();
	try
	{
		if(!m_pRecordset->BOF)
			m_pRecordset->MoveFirst();
		else
		{
			//AfxMessageBox("Table is NULL");
			return TRUE;
		}
		
		while(!m_pRecordset->adoEOF)
		{
			var = m_pRecordset->GetCollect("Classname"); // txt
			if(var.vt != VT_NULL)
				csTmp = (LPCSTR)_bstr_t(var);
			
			m_cmbFlow.AddString( csTmp );
			
			m_pRecordset->MoveNext();
		}
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}
	m_cmbFlow.SetCurSel( 0 );
	m_pRecordset->Close();
	

	// <> Fill ComboBox Purpose
	m_cmbFlow.GetLBText( m_cmbFlow.GetCurSel(), csTmp );

	csSQL = "SELECT Usename FROM Purpose WHERE Flowclass='" + csTmp + "' ORDER BY Usename ASC";
	var = csSQL;
	try
	{
		m_pRecordset->Open( var,					// const _variant_t & Source
			theApp.m_pConnection.GetInterfacePtr(),	// Get the Ptr of connect lib
			adOpenDynamic,
			adLockOptimistic,
			adCmdText);
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}
	
	m_cmbPurpose.ResetContent();
	try
	{
		if(!m_pRecordset->BOF)
			m_pRecordset->MoveFirst();
		else
		{
			//AfxMessageBox("Table is NULL");
			return TRUE;
		}
		
		while(!m_pRecordset->adoEOF)
		{
			var = m_pRecordset->GetCollect("Usename"); // txt
			if(var.vt != VT_NULL)
				csTmp = (LPCSTR)_bstr_t(var);
			
			m_cmbPurpose.AddString( csTmp );
			
			m_pRecordset->MoveNext();
		}
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}
	m_cmbPurpose.SetCurSel( 0 );
	m_pRecordset->Close();
	
	
	// <> Fill ComboBox Owner
	try
	{
		m_pRecordset->Open("SELECT * FROM Userinfo",   
			theApp.m_pConnection.GetInterfacePtr(),	 // Get the Ptr of connect lib
			adOpenDynamic,
			adLockOptimistic,
			adCmdText);
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}
	
	m_cmbOwner.ResetContent();
	try
	{
		if(!m_pRecordset->BOF)
			m_pRecordset->MoveFirst();
		else
		{
			//AfxMessageBox("Table is NULL");
			return TRUE;
		}
		
		while(!m_pRecordset->adoEOF)
		{
			var = m_pRecordset->GetCollect("Name"); // txt
			if(var.vt != VT_NULL)
				csTmp = (LPCSTR)_bstr_t(var);
			
			m_cmbOwner.AddString( csTmp );
			
			m_pRecordset->MoveNext();
		}
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}
	m_cmbOwner.SetCurSel( 0 );
	m_pRecordset->Close();
	
	
	// <> set current date 
	m_pickdate = CTime::GetCurrentTime();
	m_dateEnd = CTime::GetCurrentTime();

	m_edAccount.SetLimitText( MONEYEDIT_MAXLEN ); // order by account table
	m_edComment.SetLimitText( 150 );	// order by account table

	m_edCerificate.SetLimitText( 150 );	// order by Bankbook
	m_edBankName.SetLimitText( 50 );	// 


	m_stcTips = "Please input these fields for append a new record";
	
//	UpdateData( FALSE );  // Will be done in ResizeDlgByFlow() later


	// <> Open Account waiting for append
	try
	{
		m_pAccountset->Open("SELECT * FROM Account",   
			theApp.m_pConnection.GetInterfacePtr(),	 // Get the Ptr of connect lib
			adOpenDynamic,
			adLockOptimistic,
			adCmdText);
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}
	
	// <> Open Bankbook waiting for append
	try
	{
		m_pBankset->Open("SELECT * FROM Bankbook",   
			theApp.m_pConnection.GetInterfacePtr(),	 // Get the Ptr of connect lib
			adOpenDynamic,
			adLockOptimistic,
			adCmdText);
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}
	
	// <> resize dlg by flow class
	ResizeDlgByFlow();
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

// 
// Prevent append repeated record !
//--------------------------------------------------------------
void CDlgAddNew::OnAppend() 
{
	_variant_t		var;
	CTime			date, enddate;
	CString			csItem[ACCOUNT_COLUMNS];
	CString			csTemp[ACCOUNT_COLUMNS];
	CString			csDate, csExItem[ 5 ];
	INT				iPos = -1;
	BOOL			bPopSetup = FALSE;
	

	UpdateData( TRUE );

	// Get data from ctrl and fill into csTemp[] array
	m_edAccount.GetWindowText( csTemp[1] );
	if( csTemp[1].IsEmpty() )
	{
		MessageBox( "Money must be input!", "Remind", MB_ICONWARNING );
		return ;
	}
	
	m_cmbPurpose.GetLBText( m_cmbPurpose.GetCurSel(), csTemp[2] );
	
	m_cmbFlow.GetLBText( m_cmbFlow.GetCurSel(), csTemp[3] );
	// <> Extend input for Bank
	if( csTemp[3] == "Bank" ) 
	{
		m_edCerificate.GetWindowText( csExItem[0] );
		if( csExItem[0].IsEmpty() )
		{
			MessageBox( "Cerificate must be input!", "Remind", MB_ICONWARNING );
			return ;
		}
		m_edBankName.GetWindowText( csExItem[1] );
		if( csExItem[1].IsEmpty() )
		{
			MessageBox( "BankName must be input!", "Remind", MB_ICONWARNING );
			return ;
		}
		m_edBankRate.GetWindowText( csExItem[2] );
		if( csExItem[2].IsEmpty() )
		{
			MessageBox( "BankRate must be input!", "Remind", MB_ICONWARNING );
			return ;
		}
	}
		
	date = m_pickdate.GetTime();
	if( wtkGetSysLanguage() == WTK_BIG5 ) 
		csTemp[0] = date.Format( "%Y/%m/%d" );	// in BIG5 system, will be "2005/7/12"
	else
		csTemp[0] = date.Format( "%Y-%m-%d" );	// in GB system, is "2005-7-12"

	// packing date for compare, remove '/' and '0'
	csDate = csTemp[0];
	if( (csDate.GetLength() >= 9) && (csDate.GetAt(8) == '0') )
		csDate.Delete( 8, 1 );
	if( csDate.GetAt(5) == '0' ) 
		csDate.Delete( 5, 1 );
	iPos = -1;
	while( (iPos = csDate.Find( '/' )) != -1 ) 
		csDate.Delete( iPos, 1 );
	

	m_cmbOwner.GetLBText( m_cmbOwner.GetCurSel(), csTemp[4] );
	
	m_edComment.GetWindowText( csTemp[5] );
		

	// <> Get with the previous record
	if( m_bAdded )	// added record during this dlg 
	{
		// Here, this current record is the previous recod which append before.
		var = m_pAccountset->GetCollect("Amount");	// nummer
		if(var.vt != VT_NULL)
			csItem[1] = (LPCSTR)_bstr_t(var);
		
		var = m_pAccountset->GetCollect("Purpose");	// txt
		if(var.vt != VT_NULL)
			csItem[2] = (LPCSTR)_bstr_t(var);
		
		var = m_pAccountset->GetCollect("FlowClass");// txt
		if(var.vt != VT_NULL)
			csItem[3] = (LPCSTR)_bstr_t(var);
		
		var = m_pAccountset->GetCollect("Date");		// data/time	
		if(var.vt != VT_NULL)					// "2005/7/12" in BIG5, "2005-7-12" in GB 
			csItem[0] = (LPCSTR)_bstr_t(var);

		// packing date for compare, remove '/' and '0'
		if( (csItem[0].GetLength() >= 9) && (csItem[0].GetAt(8) == '0') ) 
			csItem[0].Delete( 8, 1 );
		if( csItem[0].GetAt(5) == '0' ) 
			csItem[0].Delete( 5, 1 );
		iPos = -1;
		while( (iPos = csItem[0].Find( '/' )) != -1 ) 
			csItem[0].Delete( iPos, 1 );

		var = m_pAccountset->GetCollect("Owner");	// txt
		if(var.vt != VT_NULL)
			csItem[4] = (LPCSTR)_bstr_t(var);
		
		var = m_pAccountset->GetCollect("Comment");	// txt
		if(var.vt != VT_NULL)
			csItem[5] = (LPCSTR)_bstr_t(var);
		else
			csItem[5].Empty();	// comment might be NULL in Table( Account )

		// <> Compare and remind
		//  current . vs . new added
		if( csItem[1] == csTemp[1] &&	// amount
			csItem[2] == csTemp[2] &&	// purpose
			csItem[3] == csTemp[3] &&	// flowclass
			csItem[0] == csDate	   &&	// date
			csItem[4] == csTemp[4] &&	// owner
			csItem[5] == csTemp[5] )	// comment
		{
			INT	iRet = MessageBox( "This record is full complete same as you append before!\n Do you want to append it yet?", 
									"Remind", MB_ICONWARNING|MB_YESNO );
			if( iRet != 6 ) // ok is 6
			{
				return ;
			}
		}
	}

	try
	{
		m_pAccountset->AddNew();    
		
		m_stcTips = "( ";
		var = csTemp[1];	// Money
		m_pAccountset->PutCollect( "Amount", var );	// Amount
		m_stcTips += csTemp[1];
		m_stcTips += ", ";
		
		var = csTemp[2];
		m_pAccountset->PutCollect( "Purpose", var );	// Purpose
		m_stcTips += csTemp[2];
		m_stcTips += ", ";
		
		var = csTemp[3];
		m_pAccountset->PutCollect( "Flowclass", var );	// Flowclass
		
		var = csTemp[0];
		m_pAccountset->PutCollect( "Date", var );	// Date
		m_stcTips += csTemp[0];
		m_stcTips += " )\n";
		
		var = csTemp[4];
		m_pAccountset->PutCollect( "Owner", var );	// Owner
		
		if( !csTemp[5].IsEmpty() ) 
		{
			var = csTemp[5];
			m_pAccountset->PutCollect( "Comment", var );	// Comment
		}

		m_pAccountset->Update();

		// set OK to m_stcTips
		m_stcTips +="The new record be appended successful!";
		UpdateData( FALSE );
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}

	// <> Extend input for Bank
	if( csTemp[3] == "Bank" ) 
	{
		LONG			lItemIdx;
		var = m_pAccountset->GetCollect("Index");	// LONG
		if(var.vt != VT_NULL)
			lItemIdx = (LONG)(var);	// !!! need check this convertion method !!!

		enddate = m_dateEnd.GetTime();
		if( wtkGetSysLanguage() == WTK_BIG5 ) 
		{
			csExItem[3] = enddate.Format( "%Y/%m/%d" );	// in GB system, will be "2005-7-12"
			if( (csExItem[3].GetLength() >= 9) && (csExItem[3].GetAt(8) == '0') ) 
				csExItem[3].Delete( 8, 1 );
			if( csExItem[3].GetAt(5) == '0' ) 
				csExItem[3].Delete( 5, 1 );
		}
		else
			csExItem[3] = enddate.Format( "%Y-%m-%d" );	// in GB system, is "2005-7-12"


		// <> append into Bankbook table
		try
		{
			m_pBankset->AddNew();    
			
			var = lItemIdx;	// Same as field(Idx) in Account 
			m_pBankset->PutCollect( "AccountIdx", var );	// AccountIdx
			
			var = csExItem[0];	// ZhangHao
			m_pBankset->PutCollect( "Certificate", var );	// Certificate

			var = csTemp[1];	// Money
			m_pBankset->PutCollect( "Account", var );	// Account
			
			var = csExItem[1];
			m_pBankset->PutCollect( "Bankname", var );	// Bankname
			
			var = csExItem[2];
			m_pBankset->PutCollect( "Bankrate", var );	// Bankrate
			
			var = csTemp[0];
			m_pBankset->PutCollect( "StartDate", var );	// StartDate
			
			var = csExItem[3];
			m_pBankset->PutCollect( "EndDate", var );	// EndDate
			
			var = csTemp[4];
			m_pBankset->PutCollect( "Owner", var );		// Owner
			
			csExItem[4] = IDS_BANKOP_STORE;
			var = csExItem[4];
			m_pBankset->PutCollect( "Operation", var );		// Operation

			if( !csTemp[5].IsEmpty() ) 
			{
				var = csTemp[5];
				m_pBankset->PutCollect( "Comment", var );	// Comment
			}
			
			m_pBankset->Update();
		}
		catch(_com_error *e)
		{
			AfxMessageBox(e->ErrorMessage());
		}
	}	// end if( csTemp[3] == "Bank" )
	

	// <> check date range
#ifdef _OUT_OF_DATE_NOTIFY_
	{
		CDataFile	MoneyDF( MONEY_CFG );
		CTime		ctBegDate, ctEndDate;	
		
		
		// <> date range type
		// <> begin date and end date
		ctBegDate = MoneyDF.GetInt( "begindate", "Date range" );
		ctEndDate = MoneyDF.GetInt( "enddate", "Date range" );
		
		if( (m_pickdate > ctEndDate) || (m_pickdate < ctBegDate) ) 
		{
			if( MessageBox( "The new record out of the current date range!\nWould u resetup the range for listview?", "Remind", MB_ICONQUESTION|MB_YESNO ) == IDYES ) 
			{
				bPopSetup = TRUE;
			}
		}
		
	}

	// <> CDataFile object could not be nesting.
	if( bPopSetup ) 
	{
		CPropertySheet	propsheet( "Setup" );
		CPageDateRange	CDateRange;
		CPageLoginInfo	CLoginInfo;
		
		
		propsheet.AddPage( &CDateRange );
		propsheet.AddPage( &CLoginInfo );
		
		if( propsheet.DoModal() == IDOK ) 
		{
			;
		}
	}
#endif
	
	m_bAdded = TRUE;
}


// 
//--------------------------------------------------------------
void CDlgAddNew::OnQuit() 
{
	CDialog::OnOK();
}


// 
//--------------------------------------------------------------
void CDlgAddNew::OnSelchangeCmbFlow() 
{
	_variant_t		var;
	CString			csTmp;
	CString			csSQL;

	
	// <> Fill ComboBox Purpose
	m_cmbFlow.GetLBText( m_cmbFlow.GetCurSel(), csTmp );
	
	csSQL = "SELECT Usename FROM Purpose WHERE Flowclass='" + csTmp + "' ORDER BY Usename ASC";
	var = csSQL;
	try
	{
		m_pRecordset->Open( var,					// const _variant_t & Source
			theApp.m_pConnection.GetInterfacePtr(),	// Get the Ptr of connect lib
			adOpenDynamic,
			adLockOptimistic,
			adCmdText);
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}
	
	m_cmbPurpose.ResetContent();
	try
	{
		if(!m_pRecordset->BOF)
			m_pRecordset->MoveFirst();
		else
		{
			//AfxMessageBox("Table is NULL");
			return ;
		}
		
		while(!m_pRecordset->adoEOF)
		{
			var = m_pRecordset->GetCollect("Usename"); // txt
			if(var.vt != VT_NULL)
				csTmp = (LPCSTR)_bstr_t(var);
			
			m_cmbPurpose.AddString( csTmp );
			
			m_pRecordset->MoveNext();
		}
	}
	catch(_com_error *e)
	{
		AfxMessageBox(e->ErrorMessage());
	}
	m_cmbPurpose.SetCurSel( 0 );
	m_pRecordset->Close();


	// <> resize dlg by flow class
	ResizeDlgByFlow();
}


// 
//--------------------------------------------------------------
CDlgAddNew::~CDlgAddNew()
{
	if( m_pRecordset != NULL )
	{
		if( m_pRecordset->State )
			m_pRecordset->Close();
		m_pRecordset = NULL;
	}
	
	if( m_pAccountset != NULL )
	{
		if( m_pAccountset->State )
			m_pAccountset->Close();
		m_pAccountset = NULL;
	}

	if( m_pBankset != NULL )
	{
		if( m_pBankset->State )
			m_pBankset->Close();
		m_pBankset = NULL;
	}
}

// 
// 
//--------------------------------------------------------------
void CDlgAddNew::ResizeDlgByFlow()
{
	RECT			dlgRect;
	RECT			smallRect;	// (l,t,r,b)
	CString			csTmp;
	CStatic			*pStc;
	BOOL			bEnable;
	INT				iCmdShow, iLeftSpan, iTopSpan;
	INT				i, IDstc[] = {
									IDC_STC_BANKINFO,
									IDC_STC_CERIFI,
									IDC_STC_BANKNAME,
									IDC_STC_BANKRATE,
									IDC_STC_ENDDATE
								};

	INT	iScreenW = GetSystemMetrics( SM_CXSCREEN );
	if( iScreenW >= 1024 ) 
	{
		iLeftSpan = 227;
		iTopSpan = 100;
	}
	else
	{
		iLeftSpan = 112;
		iTopSpan = 50;
	}
		
	smallRect.left		= 4 + iLeftSpan;
	smallRect.top		= 48 + iTopSpan;
	smallRect.right		= 576 + iLeftSpan;
	smallRect.bottom	= 426 + iTopSpan;
	
	m_cmbFlow.GetLBText( m_cmbFlow.GetCurSel(), csTmp );
	if( csTmp == "Bank" ) 
	{
		m_stcDateBeg = "BeginDate";
		dlgRect = m_dlgRect;
		bEnable = TRUE;
		iCmdShow = SW_SHOW;
	}
#if 0
/*	else if( csTmp == "Stock" )
	{
		m_stcDateBeg = "BeginDate";
		dlgRect = m_dlgRect;
		bEnable = TRUE;
		iCmdShow = SW_SHOW;
	}*/
#endif
	else
	{
		m_stcDateBeg = "Date";
		dlgRect = smallRect;
		bEnable = FALSE;
		iCmdShow = SW_HIDE;
	}
			
	MoveWindow( &dlgRect, TRUE );
	
	for( i=0; i<5; i++ )
	{
		pStc = (CStatic*)GetDlgItem( IDstc[i] );
		pStc->EnableWindow( bEnable );
		pStc->ShowWindow( iCmdShow );
	}
	m_edCerificate.EnableWindow( bEnable );
	m_edCerificate.ShowWindow( iCmdShow );
	
	m_edBankRate.EnableWindow( bEnable );
	m_edBankRate.ShowWindow( iCmdShow );
	
	m_edBankName.EnableWindow( bEnable );
	m_edBankName.ShowWindow( iCmdShow );
	
	CDateTimeCtrl*  pDateEnd = (CDateTimeCtrl*)GetDlgItem( IDC_DATE_END );
	pDateEnd->EnableWindow( bEnable );
	pDateEnd->ShowWindow( iCmdShow );
	
	UpdateData( FALSE );
}
